const express = require('express')
const path = require('path')
const fs = require('fs')
const {
  createProxyMiddleware
} = require('http-proxy-middleware');
const app = express()
const port = 8889

// const proxyMap = {
//   dev: 'http://192.168.2.242:8281',
//   test: 'http://192.168.2.112:8281',
//   dev233: 'http://192.168.2.233:8281',
//   hq: 'http://121.40.210.64:8281',
//   hbx: 'http://192.168.2.70:36100',
//   ytj: 'http://192.168.2.178:8281',
// }

// vue页面
app.use('/ilink-zhxf-h5', createProxyMiddleware({
  target: 'http://localhost:3001',
  changeOrigin: true
}));

app.use('/ilink-app-h5-zd/static', createProxyMiddleware({
  target: 'http://localhost:' + port,
  changeOrigin: true,
  pathRewrite: {
    '/ilink-app-h5-zd/static/': '/static/'
  }
}));

app.use('/ilink-app-h5-zd/json', createProxyMiddleware({
  target: 'http://localhost:' + port,
  changeOrigin: true,
  pathRewrite: {
    '/ilink-app-h5-zd/json/': '/json/'
  }
}));

// jquery页面
app.use(express.static('ilink-app-h5-zd'))

app.get('/ilink-fe-config/zhxf-app/config.js', function (req, res, next) {
  var options = {
    root: path.join(__dirname, 'ilink-app-h5-zd'),
    dotfiles: 'deny',
    headers: {
      'x-timestamp': Date.now(),
      'x-sent': true
    }
  }
  var fileName = 'config.js'
  res.sendFile(fileName, options, function (err) {
    if (err) {
      next(err)
    } else {
      console.log('Sent:', fileName)
    }
  })
})

const proxyRouter = () => {
  return fs.readFileSync(process.cwd() + '/target.env', 'utf8')
}

// 后端接口
app.use('/app', createProxyMiddleware({
  target: 'http://xxx',
  changeOrigin: true,
  router: proxyRouter
}));

app.use('/app-v3', createProxyMiddleware({
  target: 'http://xxx',
  changeOrigin: true,
  router: proxyRouter
}));

app.use('/ilink-fe-config', createProxyMiddleware({
  target: 'http://xxx',
  changeOrigin: true,
  router: proxyRouter
}));

app.use('/ilink-file', createProxyMiddleware({
  target: 'http://xxx',
  changeOrigin: true,
  router: proxyRouter
}));

app.use('/staticRes', createProxyMiddleware({
  target: 'http://xxx',
  changeOrigin: true,
  router: proxyRouter
}));

app.use('/artemis', createProxyMiddleware({
  target: 'https://fangke.wnmc.edu.cn',
  changeOrigin: true,
}));

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})